//
//  PostDailyVC.swift
//  MM2
//
//  Created by 李成明 on 2022/1/10.
//

import UIKit
import CLImagePickerTool

class PostDailyVC: MViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    private lazy var navBar: MNavBar = {
        let view = MNavBar(frame: CGRect(x: 0, y: kStateBarHeight, width: kScreenWidth, height: kNaviBarHeight))
        view.back { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }.title = "发布动态"
        return view
    }()
    
    private lazy var postBtn: UIButton = {
        let view = UIButton()
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 8
        view.layer.borderWidth = 1
        view.layer.borderColor = mainColor.cgColor
        view.titleLabel?.font = .systemFont(ofSize: 16)
        view.setTitleColor(mainColor, for: .normal)
        view.setTitleColor(.initWithRGB(215, 100, 72), for: .highlighted)
        view.setTitle("发布", for: .normal)
        view.isHighlighted = false
        view.addTarget(self, action: #selector(postClickAction), for: .touchUpInside)
        view.isUserInteractionEnabled = false
        return view
    }()
    
    private lazy var textView: UITextView = {
        let view = UITextView()
        view.delegate = self
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 10
        view.layer.borderColor = mainColor.cgColor
        view.layer.borderWidth = 1
        view.font = .systemFont(ofSize: 16)
        return view
    }()
    
    private lazy var placeHolder: UILabel = {
        let view = UILabel()
        view.font = .systemFont(ofSize: 16)
        view.textColor = mainColor
        view.text = "说点什么吧～"
        return view
    }()
    
    private var textLimitLabel: UILabel = {
        let view = UILabel()
        view.font = .systemFont(ofSize: 13)
        view.textAlignment = .right
        view.textColor = mainColor
        view.text = "0/300"
        return view
    }()
    
    private lazy var addPhotoView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "rank_add_photo_img"))
        view.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(addPhotoAction))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    private lazy var imageShowView: DailyImgShowView = {
        let view = DailyImgShowView(frame: CGRect.zero)
        view.isHidden = true
        view.addImgClick { [weak self] _ in
            self?.addPhotoAction()
        }.isAddingImg = true
        return view
    }()
    
    private var canPostClick = false {
        didSet {
            postBtn.isUserInteractionEnabled = canPostClick
            postBtn.isHighlighted = canPostClick
            postBtn.layer.borderColor = canPostClick ? UIColor.initWithRGB(215, 100, 72).cgColor : mainColor.cgColor
        }
    }
    
    private var showPlaceHolder = true {
        didSet {
            placeHolder.isHidden = !showPlaceHolder
        }
    }
}

extension PostDailyVC: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        showPlaceHolder = textView.text.isEmpty
        canPostClick = !textView.text.isEmpty
        textLimitLabel.text = "\(textView.text.count)/300"
        
        if textView.text.count >= 300 {
            guard let str = textView.text else { return }
            let index = str.index(str.startIndex, offsetBy: 299)
            textView.text = String(str[str.startIndex...index])
        }
    }
}

extension PostDailyVC {
    private func setupUI() {
        view.addsubViews([navBar, textView, imageShowView, addPhotoView])
        navBar.addSubview(postBtn)
        textView.addsubViews([placeHolder, textLimitLabel])
        
        postBtn.snp.makeConstraints { make in
            make.right.equalTo(navBar).offset(-16)
            make.centerY.equalTo(navBar)
            make.size.equalTo(CGSize(width: 60, height: 30))
        }
        
        var y = kStateAndNavH + 20
        textLimitLabel.frame = CGRect(x: 0, y: 280, width: kScreenWidth - 32 - 8, height: 20)
        placeHolder.frame = CGRect(x: 8, y: 10, width: 100, height: 20)
        textView.frame = CGRect(x: 16, y: y, width: kScreenWidth - 32, height: 300)
        
        y += (300 + 10)
        addPhotoView.frame = CGRect(x: 16, y: y, width: 160, height: 160)
        imageShowView.frame = CGRect(x: 16, y: y, width: kScreenWidth - 32, height: imageShowView.viewHeight)
    }
    
    @objc private func postClickAction() {
        view.showToast(text: "正在发布中...", autoDisMiss: false)
        var urlStr = ""
        for (index,img) in imageShowView.realImgArray.enumerated() {
            guard let compressData = Util.compressImageData(img: img) else { continue }
            
            let path = "image/\(User.share.userId)/\(Util.randomString())"
            if index == 0 {
                urlStr += (ossBaseUrl + path)
            } else {
                urlStr += ",\(ossBaseUrl)\(path)"
            }
            OSSManager.share.uploadSingleImg(data: compressData, path: path, completion: nil, isWaiting: false)
        }
        
        postRequest(content: textView.text ?? "", imgArrStr: urlStr)
    }
    
    @objc private func addPhotoAction() {
        let imgTool = CLImagePickerTool()
        imgTool.isHiddenVideo = true
        imgTool.cl_setupImagePickerWith(MaxImagesCount: 6, superVC: self) { asset, image in
            var imageArr: [UIImage] = []
            CLImagePickerTool.convertAssetArrToOriginImage(assetArr: asset, scale: 1) { img, _ in
                imageArr.append(img)
                if imageArr.count == asset.count {
                    self.setImageShowView(imageArr: imageArr)
                }
            } failedClouse: {
                self.view.showToast(text: "既然看到了这个，那应该是出bug了")
            }
        }
    }
    
    private func setImageShowView(imageArr: [UIImage]) {
        imageShowView.realImgArray = imageArr
        imageShowView.isHidden = false
        addPhotoView.isHidden = true
        let oldFrame = imageShowView.frame
        imageShowView.frame = CGRect(x: 16, y: oldFrame.origin.y, width: kScreenWidth - 32, height: imageShowView.viewHeight)
    }
    
    private func postRequest(content: String, imgArrStr: String) {
        MoyaNetwork.request(target: BaseApi.postDaily(content: content, imgList: imgArrStr)) { json, jsonStr in
            NotificationCenter.default.post(name: NSNotification.Name(notifiDailyChange), object: nil)
            let result = json["result"].boolValue ? "成功" : "失败"
            self.view.showToast(text: "发布\(result)")
            self.navigationController?.popViewController(animated: true)
        }
    }
}
